﻿using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering.PostProcessing;

public class SetFocusDistance : MonoBehaviour
{
    private Ray ray;
    private RaycastHit hit;
    private Camera m_camera;
    private PostProcessVolume m_PostProcessVolume;
    public DepthOfField m_DepthOfField;
    public Vector3 m_v3Rotation;
    public float smooth = 5.0F;
    public MeshRenderer m_meshRenderer;

    // Start is called before the first frame update
    void Start()
    {
        m_camera = GetComponent<Camera>();
        m_PostProcessVolume = GetComponent<PostProcessVolume>();
        m_DepthOfField = m_PostProcessVolume.profile.GetSetting<DepthOfField>();
        transform.DORotate(m_v3Rotation, 1.0f).SetLoops(-1, LoopType.Incremental).SetEase(Ease.Linear);
    }

    // Update is called once per frame
    void Update()
    {

        ray = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2));
        if (Physics.Raycast(ray, out hit))//射线发出并碰撞到外壳，那么手臂就应该朝向碰撞点
        {
            m_DepthOfField.aperture.value = Mathf.Lerp(
                m_DepthOfField.focusDistance.value,
                1.5f,
                Time.deltaTime * smooth);

            Debug.DrawLine(transform.position, hit.point);
            m_DepthOfField.focusDistance.value = Mathf.Lerp(
                m_DepthOfField.focusDistance.value,
                hit.distance + m_camera.nearClipPlane,
                Time.deltaTime * smooth);

            m_meshRenderer = hit.transform.GetComponent<MeshRenderer>();
            if (!DOTween.IsTweening(m_meshRenderer.material))
            {
                m_meshRenderer.material.DOColor(Color.red, 1.0f).SetLoops(2, LoopType.Yoyo);
            }
        }
        else
        {
            m_DepthOfField.aperture.value = Mathf.Lerp(
                m_DepthOfField.focusDistance.value, 20,
                Time.deltaTime * smooth);
            m_DepthOfField.focusDistance.value = Mathf.Lerp(
                m_DepthOfField.focusDistance.value,
                20.0f,
                Time.deltaTime * smooth);
        }
    }
}
